<template>
  <slide-view
    v-empty="!canShowDetail"
    :listener-ids="listenerIDs"
    :no-listener-ids="noListenerIDs"
    :no-listener-class="noListenerClass"
    :body-style="{padding: 0, height: '100%'}"
    xs-empty-icon="nopermission"
    :xs-empty-text="$t('crm.contacts.0d5995ef663750710369cab2598f3f65')"
    @afterEnter="viewAfterEnter"
    @close="hideView">
    <div ref="crmDetailMain" v-loading="loading" class="detail-main no-padding">
      <flexbox
        v-if="canShowDetail && detailData"
        direction="column"
        align="stretch"
        class="d-container">
        <wk-detail-header
          :subtitle="$t('crm.contacts.afe84cc4e9227e94a394a61192ab01c2')"
          :class="{'is-shadow': bodyIsScroll}"
          :title="detailData.name"
          :page-list="pageList"
          :dropdowns="handleOperations"
          @command="headerRightClick"
          @pageChange="pageChange">
          <template slot="left">
            <el-tooltip
              :content="detailData.star == 0 ? $t('crm.contacts.3bdb9ac68b8cd83b2306efef2ea0da51') : $t('crm.contacts.939a7787309a7ad882a4c1e3e1ca7539')"
              effect="dark"
              placement="top">
              <i
                v-if="detailData.star == 0"
                class="el-icon-star-off focus-icon"
                @click="toggleStar()" />
              <i
                v-else
                class="wk wk-focus-on focus-icon active"
                @click="toggleStar()" />
            </el-tooltip>
          </template>

          <template slot="right">
            <time-piece v-if="showTimer && isCall" />
            <el-button
              v-if="userInfo.loginType != 3"
              class="wk-premium-info-btn"
              data-type="Call">
              <i class="wk wk-icon-lightning-solid wk-premium-info-icon" data-type="Call" />
              <span class="wk-premium-info-label" data-type="Call">{{ $t('crm.contacts.956891e1d83c354333ab636bde359130') }}</span>
            </el-button>
            <el-button
              v-if="showTransfer"
              class="head-handle-button"
              @click="headerRightClick('transfer')">
              {{ $t('crm.contacts.0e0d992603441868176d64551b085cbc') }}
            </el-button>
            <el-button
              v-if="showEdit"
              class="head-handle-button"
              type="primary"
              @click="headerRightClick('edit')">
              {{ $t('crm.contacts.758f98da339dbde5e4f5ff4a38098376') }}
            </el-button>
          </template>
        </wk-detail-header>

        <!-- 标签 -->
        <flexbox v-if="tagInfo" wrap="wrap" class="wk-tags-content">
          <tag-view :value="tagInfo.value" :max-length="Infinity" wrap="wrap">
            <wk-tag
              v-model="tagInfo.value"
              :disabled="tagInfo.disabled"
              :placeholder="tagInfo.placeholder"
              :data="tagInfo"
              :options="tagInfo.setting"
              @change="tagChange($event)">
              <el-tooltip
                slot="reference"
                :content="$t('crm.contacts.4d055ae32e7eebdbbfeb5c84e0e95671')"
                effect="dark"
                placement="top">
                <el-button
                  type="icon"
                  size="small"
                  icon="wk wk-icon-label-solid" />
              </el-tooltip>
            </wk-tag>
          </tag-view>
        </flexbox>

        <!-- 快捷创建 -->
        <wk-quick-create-bar
          :list="activityHandle"
          @command="quickCreateClick" />

        <div class="d-container-body" @scroll="bodyScroll">
          <detail-head-base :list="headDetails" />
          <relative-stage-records
            :id="id"
            :crm-type="crmType"
            :is-stage-flow="true"
            :detail="detailData"
            @handle="detailHeadHandle" />
          <el-tabs v-model="tabCurrentName" nav-mode="more" class="top-padding">
            <el-tab-pane
              v-for="(item, index) in tabNames"
              :key="index"
              :label="item.label"
              :name="item.name"
              lazy>
              <template slot="label">
                <el-badge
                  :value="item.num"
                  :hidden="item.num <= 0"
                  type="primary">
                  {{ item.label }}
                </el-badge>
              </template>
              <component
                :is="item.name"
                :id="id"
                :ref="item.name"
                :detail="detailData"
                :type-list="logTyps"
                :crm-type="crmType"
                @handle="detailHeadHandle" />
            </el-tab-pane>
          </el-tabs>
        </div>
      </flexbox>
    </div>

    <!-- 新建编辑 -->
    <c-r-m-all-create
      v-if="crmCreateShow"
      :action="createActionInfo"
      :crm-type="createCRMType"
      @save-success="editSaveSuccess"
      @close="crmCreateShow=false" />

    <!-- 任务创建 -->
    <task-create
      v-if="taskCreateShow"
      :action="taskCreateAction"
      @save="editSaveSuccess"
      @close="taskCreateShow = false" />

    <!-- 转移 -->
    <transfer-handle
      v-if="transferDialogShow"
      :props="transferHandleProps"
      :dialog-visible.sync="transferDialogShow"
      @handle="detailHeadHandle({type: 'transfer'})" />

    <!-- 团队添加 -->
    <teams-handle
      v-if="teamsDialogShow"
      :dialog-visible.sync="teamsDialogShow"
      :props="teamsHandleProps"
      @handle="detailHeadHandle({type: 'team'})" />
  </slide-view>
</template>

<script>
import {
  crmContactsReadAPI,
  crmContactsDeleteAPI
} from '@/api/crm/contacts'

import SlideView from '@/components/SlideView'
import TransferHandle from '@/components/Page/SelectionHandle/TransferHandle' // 转移
import Activity from '../components/Activity' // 活动
import ContactsImport from './components/ContactsImport' // 重要信息
import CRMEditBaseInfo from '../components/CRMEditBaseInfo' // 联系人基本信息
import RelativeStageRecords from '../components/RelativeStageRecords' // 阶段记录
import RelativeBusiness from '../components/RelativeBusiness' // 相关商机
import RelativeHandle from '../components/RelativeHandle' // 相关操作
import RelativeFiles from '../components/RelativeFiles' // 相关附件
import RelativeTeam from '../components/RelativeTeam' // 团队成员

import CRMAllCreate from '../components/CRMAllCreate' // 新建页面
import TaskCreate from '@/views/oa/taskExamine/task/Create'
import DetailMixin from '../mixins/Detail'
import { mapGetters } from 'vuex'

export default {
  // 联系人管理 的 联系人详情
  name: 'ContactsDetail',
  components: {
    SlideView,
    TransferHandle,
    RelativeStageRecords,
    Activity,
    CRMEditBaseInfo,
    RelativeBusiness,
    RelativeHandle,
    RelativeFiles,
    RelativeTeam,
    CRMAllCreate,
    TaskCreate,
    ContactsImport
  },
  mixins: [DetailMixin],
  props: {
    // 详情信息id
    id: [String, Number],
    // 监听的dom 进行隐藏详情
    listenerIDs: {
      type: Array,
      default: () => {
        return ['crm-main-container']
      }
    },
    // 不监听
    noListenerIDs: {
      type: Array,
      default: () => {
        return []
      }
    },
    noListenerClass: {
      type: Array,
      default: () => {
        return ['el-table__body']
      }
    },
    // 呼出信息
    modelData: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      // 展示加载loading
      loading: false,
      crmType: 'contacts',
      headDetails: [],
      tabCurrentName: 'Activity'
    }
  },
  computed: {
    ...mapGetters([
      'isWxUser'
    ]),
    // 活动操作
    activityHandle() {
      const temps = [
        {
          command: 'task',
          icon: 'wk wk-icon-task-line',
          label: this.$t('crm.contacts.c21662cadf20d9bcd2ca02b2409f4388'),
          auth: 'oa.taskExamine'
        }, {
          command: 'business',
          icon: 'wk wk-business-line',
          label: this.$t('crm.contacts.c84cd707bf16949840d2e206839251be'),
          auth: 'crm.business.save'
        }, {
          command: 'contract',
          icon: 'wk wk-contract-line',
          label: this.$t('crm.contacts.2d26337d18e17c7e49a76f9ed4f72cc5'),
          auth: 'crm.contract.save'
        }, {
          command: 'receivables',
          icon: 'wk wk-receivables-line',
          label: this.$t('crm.contacts.ff5661df09a4672219bcae53be25cd81'),
          auth: 'crm.receivables.save'
        },
        {
          command: 'team',
          icon: 'wk wk-icon-s-seas-line',
          label: '添加团队成员',
          auth: `crm.${this.crmType}.teamsave`
        }
      ]

      // if (this.canCreateFollowRecord) {
      //   temps = [{
      //     command: 'log',
      //     label: '写跟进'
      //   }].concat(temps)
      // }

      return temps.filter(item => {
        return !item.auth || this.$auth(item.auth)
      })
    },

    // 可操作选项
    handleOperations() {
      return this.getOperations(['delete'])
    },

    // tabs
    tabNames() {
      var tempsTabs = []
      tempsTabs.push({ label: this.$t('crm.contacts.b870144f1379550347c92650d35a0e33'), name: 'Activity' })
      if (this.crm.contacts && this.crm.contacts.read) {
        tempsTabs.push({ label: this.$t('crm.contacts.49d1684e9020c2c87a639df7eb6e5c49'), name: 'CRMEditBaseInfo' })
      }

      tempsTabs.push({ label: this.$t('crm.contacts.12b7b3921e781c4d4db66255c20feea7'), name: 'RelativeTeam', num: this.tabsNumber.memberCount })

      if (this.crm.business && this.crm.business.index) {
        tempsTabs.push({ label: this.$t('crm.contacts.b23d70792c66dca5a99eaaad2c451ef3'), name: 'RelativeBusiness', num: this.tabsNumber.businessCount })
      }
      tempsTabs.push({ label: this.$t('crm.contacts.bed6a3c7178a11ddb2b6655227d18f9a'), name: 'RelativeFiles', num: this.tabsNumber.fileCount })
      if (this.userInfo.loginType != 3) {
        tempsTabs.push({ label: this.$t('crm.contacts.9a473007fc206f06795729e7bd01d27b'), name: 'RelativeHandle', num: 0 })
      }
      // if (this.statusShow) {
      //   tempsTabs.unshift({ label: '阶段记录', name: 'RelativeStageRecords' })
      // }
      return tempsTabs
    },

    // 根据记录筛选
    logTyps() {
      let logTypslist = []
      logTypslist = [{
        icon: 'all',
        color: '#2362FB',
        command: '',
        label: this.$t('crm.contacts.2aa476685e617c80f233da9ac3a6e5ac')
      }, {
        icon: 'contacts',
        color: '#27BA4A',
        command: 3,
        label: this.$t('crm.contacts.52d51858cefa20e2d4ca5b4c0869efd1')
      }, {
        icon: 'o-task',
        color: '#D376FF',
        command: 11,
        label: this.$t('crm.contacts.0223aadafd2b408b2610302acb59ee57')
      }, {
        icon: 'log',
        color: '#5864FF',
        command: 8,
        label: this.$t('crm.contacts.faade21207eec3cb35e9f9df2626a3e5')
      }, {
        icon: 'approve',
        color: '#9376FF',
        command: 9,
        label: this.$t('crm.contacts.bb84d16e85c18a9f1a1cefc36aa53774')
      }]
      if (this.$store.state.crm.isCall) {
        logTypslist.push({
          icon: 'phone',
          color: '#9376FF',
          command: 13,
          label: this.$t('crm.contacts.d8736985767917ffdda3308a15bf3d07')
        })
      }
      return logTypslist
    },

    // 客户ID
    customerId() {
      return this.detailData ? this.detailData.customerId || '' : ''
    }
  },
  mounted() {},
  methods: {
    /**
     * 详情
     */
    getDetial() {
      this.loading = true
      crmContactsReadAPI({
        contactsId: this.id
      })
        .then(res => {
          this.loading = false
          const resData = res.data || {}
          this.detailData = resData
          // 负责人
          this.headDetails = [{ title: this.$t('crm.contacts.d3938e213ac3cbf8d58206c615355d61'), value: resData.customerName },
            { title: this.$t('crm.contacts.ec358d40711dc22a3116e37cd82bd2c8'), value: resData.post },
            { title: this.$t('crm.contacts.697b592ec555eb98626c5be2d997d242'), value: resData.mobile },
            { title: this.$t('crm.contacts.0fca66ff045bdb300a51351c837e90a2'), value: resData.createTime }]
        })
        .catch(() => {
          this.loading = false
          this.hideView()
        })
    },

    /**
     * 关闭
     */
    hideView() {
      this.$emit('hide-view')
    },

    /* ------------------------ 头部事件 ------------------------ */
    /**
     * @description: 头部右侧点击事件
     * @param {*}
     * @return {*}
     */
    headerRightClick(type) {
      if (type === 'transfer') {
        this.transferDialogShow = true
      } else if (type === 'edit') {
        this.createCRMType = this.crmType
        this.createActionInfo = {
          type: 'update',
          id: this.id,
          batchId: this.detailData.batchId
        }
        this.crmCreateShow = true
      } else if (type == 'delete') {
        this.$confirm(
          this.$t('crm.contacts.1a17a76d1ecba47941974920b068a12a'),
          this.$t('crm.contacts.64c9612550b1d1e57de09b8f86c87b23'),
          {
            confirmButtonText: this.$t('crm.contacts.a1c3e6e4bb3ee041edc2021b24cc4d47'),
            cancelButtonText: this.$t('crm.contacts.580f0037e9a8caa3ae9eb68c63e35fb6'),
            type: 'warning'
          }
        )
          .then(() => {
            crmContactsDeleteAPI([this.id])
              .then(res => {
                this.$message({
                  type: 'success',
                  message: this.$t('crm.contacts.63bf7604689f0ef216d1001cd3787cf3')
                })
                this.detailHeadHandle({ type })
              })
              .catch(() => {})
          })
          .catch(() => {})
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import "../styles/crmdetail.scss";

.d-container-body {
  margin-top: 8px;
}
</style>
